/**
 * Created by zhiyuan
 */
var stopCombatting = false;
var stopDate = false;
var newOrderTipTimerId;
var orderParam = {
    inited: false, // 初始化页面是否完成
    timeFlag:false,//时间查询全部的标识
    cache: {}, // 列表缓存数据
    params: {
        pageNo: 1,
        pageSize: 20,
        payType: '', //支付方式
        orderStatus: '',//订单状态
        orderSource:'',//订单来源
        shopId: '',//门店Id
        startDate:'',
        endDate:'',
        shopName: '',
        tradeDate: ''//订单交易日期:yyyy-MM-dd
    } ,// 查询参数
    selectedOption:'1', //缓存选择的tab标签, 1:订单明细, 2:异常订单
    bossOpenDate: new Date(new Date().setFullYear(new Date().getFullYear() - 2))
};
(function(doc, win) {
    this.configInfo = {
        "minus" : {
            "app.home": {
                className : "",
                id : "index",
                className1 : "zhk-tab_home",
                className2 : "zhk-tab_home_active",
                name : "首页"
            },
            "app.marketingcenter":{
                className : "",
                id : "activity",
                className1 : "zhk-tab_yx",
                className2 : "zhk-tab_yx_active",
                name : "营销中心"
            },
            "app.order": {
                className : "active",
                id : "order",
                className1 : "zhk-tab_order",
                className2 : "zhk-tab_order_active",
                name : "订单"
            },
            "app.my": {
                className : "",
                id : "my",
                className1 : "zhk-tab_user",
                className2 : "zhk-tab_user_active",
                name : "我的"
            }
        }
    };
    var BindEvent = function(){
       //下拉刷新的方法
        refreshItem({
            "target": "#orderPage .page-body",
            "callBack": function(reset) {
                orderParam.params.pageNo=1;
                orderParam.params.pageSize=20;
                orderParam.params.startDate=dateFormate(-6);
                orderParam.params.endDate=currentTime();
                queryOrderFunction(reset);
            }
        });
        addMoreItem({
            "target": "#orderPage .page-body",
            "callBack": function(reset) {
                orderParam.params.pageNo++;
                var controller = new OrderController();
                if (orderParam.selectedOption == '1') {
                    controller.getOrderStatisticsList(orderParam.params, reset);
                } else if (orderParam.selectedOption == '2') {
                    controller.getExceptionOrderList(orderParam.params, reset);
                }
            }
        });
        //点击刷新的方法
        initToolbarRefresh();
        $(document).on('newOrder',function(){
            if($('#orderPage').length !==0){
                $('#orderPage #orderPageNewOrder').css({display:'block'});
                if(newOrderTipTimerId){
                    clearTimeout(newOrderTipTimerId);
                }
                newOrderTipTimerId = setTimeout(function() {
                    $('#orderPage #orderPageNewOrder').css({display:'none'});
                    newOrderTipTimerId = '';
                }, 3000);

            }
        });
        $(document).on('click','#orderPage #orderPageNewOrder',function(){
            orderParam.params.pageNo=1;
            orderParam.params.pageSize=20;
            orderParam.params.startDate=dateFormate(-6);
            orderParam.params.endDate=currentTime();
            queryOrderFunction();
        });
        $(document).on('refresh-order',function(){
            orderParam.params.pageNo=1;
            orderParam.params.pageSize=20;
            orderParam.params.startDate=dateFormate(-6);
            orderParam.params.endDate=currentTime();
            queryOrderFunction();
        });
    };

    if($('#orderPage').length){
        BindEvent();
    }

    $(doc).on("pageAnimationStart", "#orderPage", function(){
        BindEvent();
    });

    // sui 页面就绪时间
    $(doc).on("pageInit", "#orderPage", function(e, pageId, $page, isBack) {
        if (isBack) {
            $('#orderPage .s-date')[0].id = 'select-date';
            if (orderFilterParam.params && orderFilterParam.params.orderStatus === orderParam.params.orderStatus &&
                orderFilterParam.params.payType === orderParam.params.payType &&
                orderFilterParam.params.shopId === orderParam.params.shopId &&
                orderFilterParam.params.orderSource === orderParam.params.orderSource) {

            } else {
                    var tradeDate = "";
                    var startTime = dateFormate(-29);
                    var entTime = currentTime();
                if(!orderParam.timeFlag){
                    tradeDate=orderParam.params.tradeDate;
                    if(tradeDate == '' || tradeDate == null){
                    startTime = dateFormate(-6);
                    entTime = currentTime();
                    }
                }
                orderParam.params = {
                    pageNo: 1,
                    pageSize: 20,
                    orderStatus: orderFilterParam.params.orderStatus,
                    payType: orderFilterParam.params.payType,
                    shopId: orderFilterParam.params.shopId,
                    shopName: orderFilterParam.params.shopName,
                    orderSource: orderFilterParam.params.orderSource,
                    tradeDate: tradeDate,
                    startDate: startTime,
                    endDate:entTime
                };
                $("#orderPage .page-body .no-more-order").remove();
                var controller = new OrderController();
                if (orderParam.selectedOption == '1') {
                    controller.getOrderStatisticsList(orderParam.params);
                } else if (orderParam.selectedOption == '2') {
                    controller.getExceptionOrderList(orderParam.params);
                }
            }
            //设置选择icon
            setFilterIcon(orderFilterParam.singleShop);

        } else {
            orderFilterParam.params.payType = "";
            orderFilterParam.params.orderStatus = "";
            orderFilterParam.params.orderSource = "";
            orderFilterParam.params.shopId = "";
            orderFilterParam.params.shopName = "";
            //追加get请求的参数
            var startTime = dateFormate(-6);
            var entTime = currentTime();
            orderParam.params = {
                pageNo: 1,
                pageSize: 20,
                payType: '', //支付方式
                orderStatus: '',//订单状态
                orderSource:'',//订单来源
                shopId: '',//门店Id
                shopName: '',//门店名称
                startDate:startTime,
                endDate:entTime,
                tradeDate: ''//订单交易日期
            };
            $("#orderPage .page-body .no-more-order").remove();
            var controller = new OrderController();
            if (orderParam.selectedOption == '1') {
                controller.getOrderStatisticsList(orderParam.params);
            } else if (orderParam.selectedOption == '2') {
                controller.getExceptionOrderList(orderParam.params);
            }
            //下滑日期行固定
            refreshFunc();
            //初始化日期插件
            controller.date(initDateFuntion);
            //设置选择icon
            setFilterIcon(true);
        }
        var user = sessionStorageClient.getJSON("user");
        if(user.authMinus){
            var authMinusData={}
            authMinusData=getOAuthMinus(authMinusData,user.authMinus);//获取权限项
            authority(authMinusData);
        }
    });

    //获取权限
    function  getOAuthMinus(result,authMinus){
        var minusHtml = [];
        var indexCode = [];
        if (authMinus != null && authMinus.length > 0) {
            for (var i = 0; i < authMinus.length; i++) {
                var minus = authMinus[i];
                minusHtml.push(minus.taskCode);
                if (minus.taskCode == "app.order") {//我的权限项
					if (minus.children!= null && minus.children.length > 0) {
                       for (var i = 0; i < minus.children.length; i++) {
                          indexCode.push(minus.children[i].taskCode);
                         }
                       }
                }
            }
            result.minusHtml = minusHtml;
        }
        result.indexCode = indexCode;
        return result;
    }

    function authority(authMinusData){
    	//判断查询功能模块权限
		if($.inArray("app.marketingcenter", authMinusData.minusHtml) > -1 ){ //判断是否可以查看营销中心模块
            $("#orderPage .marketingcenter").show();//显示模块
        }else{
            $("#orderPage .marketingcenter").hide();//隐藏模块
        }

	}
    // 跳转订单详情
    $(doc).on("click", "#orderPage .list li", function(){
        if(!stopCombatting){
            stopCombatting = true;
            var shopId = $(this).attr("shopId");
            var orderId = $(this).attr("orderId");
            var orderType = $(this).attr("orderType");
            var orderStatus = $(this).attr("orderStatus");
            $.router.load("order_details.html?orderId=" + orderId +"&orderType="+ orderType +"&shopId="+ shopId +"&orderStatus="+ orderStatus);
            setTimeout(function() {
                stopCombatting = false;
            }, 1000);
        }
    });
    // 跳转订单筛选页
    $(doc).on("click", "#sel-order-condition", function(){
        CommonUtil.injectParamObject(orderParam);
        $('#orderPage #select-date')[0].id = '';
        $.router.load("order_filter.html");
    });

    //tab切换
    $(document).on('click','#orderPage .scroll-view .tab-wrap li',function(){
        $(".tab-wrap-last").empty();
        $('.order .page-body').scrollTop(0);
        $(this).addClass("selected").siblings().removeClass("selected");
        switch($(this).index()){
            case 0:
                $('.order .tab2').hide();
                $('.order .tab1').show();
                var firstItem = $(".tab1 .item").eq(0).find(".title");
                $('.tab-wrap-last').append(firstItem.clone(true));
                orderParam.selectedOption = '1';
                disableAddMoreItem($("#orderPage .page-body"));
                $('#orderPage #select-date').show();
                break;
            case 1:
                $('.order .tab1').hide();
                $('.order .tab2').show();
                var firstItem = $(".tab2 .item").eq(0).find(".title");
                $('.tab-wrap-last').append(firstItem.clone(true));
                orderParam.selectedOption = '2';
                disableAddMoreItem($("#orderPage .page-body"));
                $('#orderPage #select-date').hide();
                break;
            default:
                $('.order .tab2').hide();
                $('.order .tab1').show();
                orderParam.selectedOption = '1';
                $('#orderPage #select-date').show();
                break;
        }
        //渲染数据
        orderPageTabFunc(this);
        //设置选择icon
        setFilterIcon(true);
    })

    // tab切换
    var orderPageTabFunc = function(tabObject){
        var startTime =  dateFormate(-6);
        var entTime = currentTime();
        orderParam.params = {
            pageNo: 1,
            pageSize: 20,
            payType: '', //支付方式
            orderStatus: '',//订单状态
            orderSource:'',//订单来源
            shopId: '',//门店Id
            shopName: '',//门店名称S
            startDate:startTime,
            endDate:entTime,
            tradeDate: ''//订单交易日期
        };

        var tab = $(tabObject).attr("tab");
        var controller = new OrderController();
        if (tab == 'orderListTab') {
            controller.getOrderStatisticsList(orderParam.params);
        } else if (tab == 'excepOrderListTab') {
            controller.getExceptionOrderList(orderParam.params);
        }
        //清除查询页面的查询条件
        clearOrderFilterParam();
    }

    //查询订单列表数据
    var queryOrderFunction = function(reset) {
        var controller = new OrderController();
        debugger
        if (orderParam.selectedOption == '1') {
            $('#orderStatisticsListDiv').empty();
            disableAddMoreItem("#orderPage .page-body");
            $('#orderPage .no-more-order').remove();
            controller.getOrderStatisticsList(orderParam.params,reset);
        } else if (orderParam.selectedOption == '2') {
            $('#exceptionOrderListDiv').empty();
            disableAddMoreItem("#orderPage .page-body");
            $('#orderPage .no-more-order').remove();
            controller.getExceptionOrderList(orderParam.params,reset);
        }
    }

    //下滑日期行固定
    var refreshFunc = function() {
        var htop = $(".header").height()+$(".tab-wrap").height();
        $(".page-body").scroll(function() {
            if($(this).scrollTop()!=0){
                //tab1
                $(".tab-wrap-last").removeClass('hide');
                for(var i=0;i<$(".tab1 .item").length;i++){
                    var itemTop = $(".tab1 .item").eq(i).offset().top-htop;
                    var itemHeight = $(".tab1 .item").eq(i).height();
                    var itemTitle=$(".tab1 .item").eq(i).find(".title");
                    var itemTitleHeight=itemTitle.height();
                    if(itemTop<=5&&itemTop>=-itemHeight){
                        $(".tab-wrap-last").empty();
                        if($('.tab-wrap-last').html() == ""){
                           $('.tab-wrap-last').append(itemTitle.clone(true))
                        }
                    }
                }
                //tab2
                for(var i=0;i<$(".tab2 .item").length;i++){
                    var itemTop = $(".tab2 .item").eq(i).offset().top-htop;
                    var itemHeight = $(".tab2 .item").eq(i).height()
                    var itemTitle=$(".tab2 .item").eq(i).find(".title");
                    var itemTitleHeight=itemTitle.height()
                    if(itemTop<=5&&itemTop>-itemHeight){
                        $(".tab-wrap-last").empty();
                        if($('.tab-wrap-last').html() == ""){
                           $('.tab-wrap-last').append(itemTitle.clone(true))
                        }
                    }
                }
            }
            if($(this).scrollTop()<1){
                $(".tab-wrap-last").addClass('hide');
            }
       })
    }
    $(doc).on("click", "#orderPage #select-date", function(){
        $('#orderPage #select-date').mobiscroll('show')
    });
    //初始化日期插件
    var initDateFuntion = function() {
        //日期选择
        var orderPageCurrYear = new Date().getFullYear();
        $('#orderPage #select-date').mobiscroll().date({
            theme: 'ios',
            showOnTap:false,
            model: 'scroller',
            lang: 'zh',
            display: 'bottom',
            dateFormat: 'yy-mm-dd',
            yearSuffix:'年',
            monthSuffix:'月',
            daySuffix:'日',
            closeOnOverlay:false,
            buttons:[{text:'确定',handler:'set'},{text:'取消',handler:'cancel'},{text:'近30天',handler:'clear'}],
            defaultValue: new Date(new Date().setFullYear(orderPageCurrYear)),
            maxDate: new Date(new Date().setFullYear(orderPageCurrYear)),
            minDate: orderParam.bossOpenDate,
            onClose: function (event, inst) {
                if(inst == 'set') {
                    if (orderParam.params.tradeDate != event) {
                        orderParam.params.pageNo=1;
                        orderParam.params.pageSize=20;
                        orderParam.params.tradeDate = event;
                        orderParam.params.startDate='';
                        orderParam.params.endDate='';
                        orderParam.timeFlag=false;
                        queryOrderFunction();
                    }
                } else if (inst == 'clear') {
                        orderParam.params.pageNo=1;
                        orderParam.params.pageSize=20;
                        orderParam.params.tradeDate='';
                        orderParam.params.startDate=dateFormate(-29);
                        orderParam.params.endDate=currentTime;
                        orderParam.timeFlag=true;
                        queryOrderFunction();
                }
            }
        });
    }

    //设置筛选标签样式
    var setFilterIcon = function (singleShop) {
        if (orderParam.params.orderStatus != ''
            || orderParam.params.payType != '' || orderParam.params.orderSource != '') {
            $('#orderPage .header .right .zhk-nav_filter').addClass("headIconUsed");
            return;
        }
        if (orderParam.params.shopId != '' && !singleShop) {
            $('#orderPage .header .right .zhk-nav_filter').addClass("headIconUsed");
            return;
        }

        $('#orderPage .header .right .zhk-nav_filter').removeClass("headIconUsed");
    }
    //当前时间
    var  currentTime= function(){
        var date1 = new Date();
        var time1=date1.getFullYear();//time1表示当前时间
        if(date1.getMonth() + 1 < 10){
            time1 = time1 +"-0"+(date1.getMonth()+1);
        }else{
            time1 = time1 +"-"+(date1.getMonth()+1);
        }
        if(date1.getDate() < 10){
            time1 = time1 +"-0"+(date1.getDate());
        }else{
            time1 = time1 +"-"+(date1.getDate());
        }
        return time1;
    }
    //一周前时间
    var dateFormate = function(aa){
        var date1 = new Date();
        var time1=date1.getFullYear()+"-"+(date1.getMonth()+1)+"-"+date1.getDate();//time1表示当前时间
        var date2 = new Date(date1);
        date2.setDate(date1.getDate()+aa);
        var time2 = date2.getFullYear();
        if(date2.getMonth() + 1 < 10){
            time2 = time2 +"-0"+(date2.getMonth()+1);
        }else{
            time2 = time2 +"-"+(date2.getMonth()+1);
        }
        if(date2.getDate() < 10){
            time2 = time2 +"-0"+(date2.getDate());
        }else{
            time2 = time2 +"-"+(date2.getDate());
        }
        return time2;
    }

    //清除查询页面的查询条件
    var clearOrderFilterParam = function() {
        orderFilterParam.params.orderStatus = '';
        orderFilterParam.params.payType = '';
        orderFilterParam.params.shopId = '';
        orderFilterParam.params.orderSource = '';
    }

    $(document).on("click","#orderPage #linkToIndex",function(e){
        window.location.href = '../vuepages/index.html#/?'+window.App.urlParam;
    });
})(document, window);
